﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DTO;
using BLL;
using System.Collections;

namespace HDT.GUI
{
    public partial class FrmSuaMH : Form
    {
        private string PRODUCT_IMAGE_FOLDER = "Image\\_Product\\";
        public delegate void MyDelegate();
        public MyDelegate refreshForm;

        MatHangDTO matHang;
        List<LoaiMatHangDTO> dsLoai;
        int giaNY;
        Hashtable dsCK;
        
        public FrmSuaMH()
        {
            InitializeComponent();
            matHang = new MatHangDTO();
            dsLoai = new List<LoaiMatHangDTO>();
            dsCK = new Hashtable();
        }

        public FrmSuaMH(string maMH)
            : this()
        {
            try
            {
                matHang = new MatHangBLL().GetByID(maMH);
                giaNY = matHang.Gia.Gia;
                dsCK = GetDSChietKhau(matHang.DSChietKhau);
            }
            catch { }
        }

        private Hashtable GetDSChietKhau(List<ChietKhauDTO> dsChietKhau)
        {
            Hashtable temp = new Hashtable();
            foreach (ChietKhauDTO ck in dsChietKhau)
            {
                temp.Add((int)ck.SoLuongToiThieu, ck.TyLeChietKhau);
            }
            return temp;
        }

        private void btnThemCK_Click(object sender, EventArgs e)
        {
            FrmThemCK frm_ThemCK = new FrmThemCK();
            frm_ThemCK.ShowDialog();
        }

        private void FrmSuaMH_Load(object sender, EventArgs e)
        {
            LoadLoaiMatHangInfo();
            LoadProductInfo();
            btnLuu.Enabled = false;
        }

        private void LoadLoaiMatHangInfo()
        {
            try
            {
                dsLoai = new LoaiMatHangBLL().Select("TrangThai = 1");
                foreach (LoaiMatHangDTO loai in dsLoai)
                {
                    cboLoaiMH.Items.Add(loai.TenLoaiMatHang);
                }
                cboLoaiMH.SelectedIndex = 0;
            }
            catch { }
        }

        private void ShowChietKhau()
        {
            dgvCK.Rows.Clear();
            foreach(DictionaryEntry entry in dsCK){
                DataGridViewRow row = (DataGridViewRow)dgvCK.Rows[0].Clone();
                row.Cells[0].Value = entry.Key;
                row.Cells[1].Value = ((double)entry.Value).ToString("#,##0.00 %");
                dgvCK.Rows.Add(row);
            }
        }

        private void AddChietKhau(int SoLuong, double TyLe)
        {
            if (dsCK.Contains(SoLuong))
            {
                DialogResult dialogResult = MessageBox.Show("Số lượng tối thiểu này đã được gán tỷ lệ", "LỖI", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                dsCK.Add(SoLuong, TyLe);
                btnLuu.Enabled = true;
                ShowChietKhau();
            }
        }

        private void RemoveChietKhau(int SoLuong)
        {
            dsCK.Remove(SoLuong);
            btnLuu.Enabled = true;
            ShowChietKhau();
        }

        private void SaveProductImage(MatHangDTO matHang)
        {
            try
            {
                string path = PRODUCT_IMAGE_FOLDER + matHang.MaMatHang + ".bmp";
                picMH.Image.Save(path, System.Drawing.Imaging.ImageFormat.Bmp);
                matHang.HinhAnh = matHang.MaMatHang + ".bmp";
                new MatHangBLL().Update(matHang);
            }
            catch
            {

            }
        }

        private void LoadProductImage(string filename)
        {
            try
            {
                string path = PRODUCT_IMAGE_FOLDER + filename;
                Image img = Image.FromFile(path);
                picMH.Image = img;
            }
            catch (Exception)
            {
                picMH.Image = null;
            }
        }

        private void LoadProductInfo()
        {
            txtTenMH.Text = matHang.TenMatHang;
            txtMaMH.Text = matHang.MaMatHang;
            txtDViTinh.Text = matHang.DonViTinh;
            txtChiTiet.Text = matHang.ChiTiet;            
            numGiaBan.Value = giaNY;
            LoadProductImage(matHang.HinhAnh);
            cboLoaiMH.SelectedItem = new LoaiMatHangBLL().GetByID(matHang.MaLoaiMatHang).TenLoaiMatHang;
            cboTrangThai.SelectedIndex = matHang.TrangThai ? 0 : 1;
            ShowChietKhau();
        }

        private void dgvCK_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvCK.SelectedRows.Count > 0)
            {
                try
                {
                    int SL = int.Parse(dgvCK.SelectedRows[0].Cells[0].Value.ToString());
                    btnXoaCK.Enabled = true;
                }
                catch
                {
                    btnXoaCK.Enabled = false;
                }
            }
        }

        private void btnThemCK_Click_1(object sender, EventArgs e)
        {
            FrmThemCK f = new FrmThemCK();
            f.AddChietKhau = new FrmThemCK.MyDelegate(AddChietKhau);
            f.ShowDialog();
        }

        private void btnXoaCK_Click(object sender, EventArgs e)
        {
            try
            {
                int SL = int.Parse(dgvCK.SelectedRows[0].Cells[0].Value.ToString());
                btnXoaCK.Enabled = false;
                RemoveChietKhau(SL);
            }
            catch { }
        }

        private void picMH_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog open = new OpenFileDialog();
                open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
                if (open.ShowDialog() == DialogResult.OK)
                {
                    Bitmap bit = new Bitmap(open.FileName);
                    picMH.Image = bit;
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Không thể mở được hình", "LỖI", MessageBoxButtons.OK, MessageBoxIcon.Error);
                picMH.Image = null;
            }
            btnLuu.Enabled = true;
        } 


        private void UpdateMatHang()
        {
            matHang.TenMatHang = txtTenMH.Text.Trim();
            matHang.MaLoaiMatHang = dsLoai[cboLoaiMH.SelectedIndex].MaLoaiMatHang;
            matHang.DonViTinh = txtDViTinh.Text.Trim();
            matHang.ChiTiet = txtChiTiet.Text.Trim();
            matHang.TrangThai = cboTrangThai.SelectedIndex == 0;
            new MatHangBLL().Update(matHang);
            SaveProductImage(matHang);
        }

        private void InsertGiaNY()
        {
            GiaNiemYetDTO gia = new GiaNiemYetDTO();
            gia.MaMatHang = matHang.MaMatHang;
            gia.NgayApDung = DateTime.Now;
            gia.Gia = (int)numGiaBan.Value;
            new GiaNiemYetBLL().Insert(gia);
        }

        private void UpdateCK()
        {
            new ChietKhauBLL().Delete(matHang.DSChietKhau);
            List<ChietKhauDTO> dsChietKhau = new List<ChietKhauDTO>();
            foreach (DictionaryEntry entry in dsCK)
            {
                ChietKhauDTO chietKhau = new ChietKhauDTO();
                chietKhau.MaMatHang = matHang.MaMatHang;
                chietKhau.SoLuongToiThieu = short.Parse(entry.Key.ToString());
                chietKhau.TyLeChietKhau = double.Parse(entry.Value.ToString());
                dsChietKhau.Add(chietKhau);
            }
            new ChietKhauBLL().Insert(dsChietKhau);
        }

        private void btnQuayLai_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            try
            {
                UpdateMatHang();
                InsertGiaNY();
                UpdateCK();
                MessageBox.Show("Cập nhật thành công", "THÔNG BÁO", MessageBoxButtons.OK, MessageBoxIcon.Information);
                refreshForm();
                this.Dispose();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, "LỖI", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txt_TextChanged(object sender, EventArgs e)
        {
            btnLuu.Enabled = true;
        }

        //private void
    }
}
